package com.manong.config.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.manong.utils.Result;
import com.manong.utils.ResultCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 李茂鑫
 * @Date 2025/1/13 15:44
 * @Descripition  匿名用户访问资源处理器，无权限资源
 */
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("/application/json;charset-UTF-8");
        //设置编码格式
        ServletOutputStream outputStream=response.getOutputStream();
        //获取输入流
        String result= JSON.toJSONString(Result.error().code(ResultCode.No_LOGIN).message("匿名用户无权限访问"), SerializerFeature.DisableCircularReferenceDetect);
        //将结果转换为json格式输出
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

